<template>
  <view>
    <view class="u-page">
      <view class="con">
        <!-- 任务发布页 -->
        <u--form
          labelPosition="left"
          labelWidth="80"
          :model="model1"
          :rules="rules"
          ref="form1"
        >

                  <u-form-item
            label="任务类型"
            prop="rwInfo.rwlx"
            borderBottom
            @click="showRwlx=true"
            ref="item1"
          >
            <u--input
              v-model="model1.rwInfo.rwlx"
              disabled
              disabledColor="#ffffff"
              placeholder="请选择任务类型"
              border="none"
            ></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>



          <u-form-item
            label="任务名称"
            require="true"
            prop="rwInfo.mc"
            borderBottom
            ref="item1"
          >
            <u--input
              v-model="model1.rwInfo.mc"
              border="none"
              placeholder="请输入任务名称"
            ></u--input>
          </u-form-item>

          <u-form-item
            label="当前定位"
            require="true"
            prop="rwInfo.address"
            borderBottom
            ref="item1"
          >
            <u--input
              v-model="model1.rwInfo.address"
              disabled
              disabledColor="#ffffff"
              border="none"
              placeholder="当前定位"
            ></u--input>
          </u-form-item>
          <u-form-item v-if='model1.rwInfo.rwlx=="工地管理任务"'
            label="所属工地"
            prop="rwInfo.ssgd"
            borderBottom
            
            ref="item1"
          >
            <u--input
              v-model="model1.rwInfo.ssgd"
              placeholder="请输入关键字后搜索工地"
              border="none"
            ></u--input>
            <u-button type="primary" size="small" slot="right" @click="selGd">搜索</u-button>
                        <!-- <u-icon
              slot="right"
              name="search"
              color="#478ef6" @click="selGd"
              size="26"
            ></u-icon> -->




          </u-form-item>

          <u-form-item
            label="截止时间"
            prop="model1.rwInfo.endTime"
            borderBottom
            @click="showTime = true"
            ref="item1"
          >
            <u--input
              v-model="model1.rwInfo.endTime"
              disabled
              disabledColor="#ffffff"
              placeholder="请选择截止时间"
              border="none"
            ></u--input>
            <u-icon slot="right" name="calendar" size="26" color="#478ef6"></u-icon>
          </u-form-item>

          <u-form-item
            label="任务描述"
            prop="model1.rwInfo.content"
            borderBottom
            ref="item1"
          >
            <u--textarea
              v-model="model1.rwInfo.content"
              placeholder="请输入任务描述"
            ></u--textarea>
          </u-form-item>

          <u-form-item
            label="指派人员"
            prop="model1.rwInfo.zpry"
            borderBottom
            @click="toTree"
            ref="item1"
          >
            <u--input
              v-model="model1.rwInfo.zpry"
              disabled
              disabledColor="#ffffff"
              placeholder="请选择指派人员"
              border="none"
            ></u--input>
            <u-icon
              slot="right"
              name="plus-circle-fill"
              color="#478ef6"
              size="26"
            ></u-icon>
          </u-form-item>

          <u-form-item
            label="现场照片"
            prop="model1.rwInfo.photo"
            borderBottom
            ref="item1"
          >
            <u-upload :fileList="pictures" @afterRead="afterFileRead($event, item)" @delete="afterFileDelete($event, item)" multiple></u-upload>
          </u-form-item>



        </u--form>

        <u-button  v-if='model1.rwInfo.rwlx=="公用管理任务"'
          color="#5ea3f1"
          size="large"
          text="发布公用管理任务"
          @click="submit2()"
        ></u-button>
        <u-button v-else
          color="#5ea3f1"
          size="large"
          text="发布"
          @click="submit1()"
        ></u-button>

        <u-action-sheet style="height: 50vh;"
          :show="showSsgd"
          :actions="actions"
          title="请选择所属工地"
          @close="showSsgd = false"
          @select="gdSelect"
        >
        </u-action-sheet>
        <u-action-sheet
          :show="showRwlx"
          :actions="actions1"
          title="请选择任务类型"
          @close="showRwlx = false"
          @select="taskSelect"
        >
        </u-action-sheet>

        <u-datetime-picker 
          :show="showTime"
          :minDate="minDate"
          v-model="defaultTime"
          mode="date"
          @cancel="showTime = false"
          @confirm="confirmTime"
        ></u-datetime-picker>
        <!-- <u-calendar :show="showTime" @confirm="confirmTime" @close="showTime = false" maxDate="2039-01-01"></u-calendar> -->
      </view>
    </view>
    <mytabbar v-if="characterType"></mytabbar>
  </view>
</template>
<script>
import getLocation from "@/utils/getLocation.js";
import { mapState, mapMutations } from "vuex";
import sceneMixins from "@/utils/sceneMixins";
import mytabbar from "@/components/tabbar/index.vue";
export default {
  options: { styleIsolation: "shared" },
  components: { mytabbar: mytabbar },
  mixins: [getLocation,sceneMixins],
  computed: {
    ...mapState(["lnglat","userInfo", "openId", "token", "characterType"]),
  },
  data() {
    return {
      showSsgd: false,
      showRwlx: false,
      showTime: false,
      showZpry: false,
      defaultTime: Number(new Date()),
     minDate: '',
     maxDate: '2039-01-01',
      model1: {
        rwInfo: {
          rwlx:'',
          mc: "",
          endTime: '',
          content: "",
          zpry: "",
          userIds: "",
          ssgd: "",
          entityId: "",
          type:'',
          address:'',
          photo:[]
        },
      },
      pictures:[],
      actions: [
        {
          name: "青阳工地1",
        },
        {
          name: "青阳工地2",
        },
        {
          name: "青阳工地3",
        },
      ],
      actions1: [
        {
          name: "公用管理任务",
        },
        {
          name: "工地管理任务",
        },
        {
          name: "其他",
        },
      ],
      rules: {
        "rwInfo.rwlx": {
          type: "string",
          required: true,
          message: "请选择任务类型",
          trigger: ["blur", "change"],
        },
        "rwInfo.mc": {
          type: "string",
          required: true,
          message: "请填写任务名称",
          trigger: ["blur", "change"],
        },
        // "rwInfo.ssgd": {
        //   type: "string",
        //   required: true,
        //   message: "请填写所属工地",
        //   trigger: ["blur", "change"],
        // },
        "rwInfo.zpry": {
          type: "string",
          required: true,
          message: "请填写指派人员",
          trigger: ["blur", "change"],
        },
      },
      radio: "",
      entityId: "",
      switchVal: false,
      position:''
    };
  },

  methods: {
    ...mapMutations(["changeTab", "changeCharacterType"]),
    gdSelect(e) {//工地选择
      this.model1.rwInfo.ssgd = e.name;
      this.model1.rwInfo.entityId = e.id;
    },
    selGd(){
      this.getGds(this.model1.rwInfo.ssgd)
    },
    taskSelect(e) {//任务选择
      this.model1.rwInfo.rwlx = e.name;
        this.model1.rwInfo.zpry=''
      if(e.name=='公用管理任务'){
        // this.model1.rwInfo.entityId=''
        this.model1.rwInfo.ssgd=''
      }
      if(e.name=='其他'){
        this.model1.rwInfo.ssgd=''
      }
      if(e.name=='工地管理任务'){
        this.model1.rwInfo.ssgd=''
      }
    },
    confirmTime(e) {
      const timeFormat = uni.$u.timeFormat
      this.model1.rwInfo.endTime = timeFormat(e.value, 'yyyy-mm-dd');
      this.showTime = false;

    },
    open() {
      // console.log('open');
    },
    close() {
      this.showZpry = false;
      // console.log('close');
    },
            afterFileRead: function(data) {
            var vm = this;
            data.file.forEach(file => {
                vm.uploadFile(file.url, res => {
                    if (res.code==0) {
                      vm.pictures.push({
                        path: res.data.src,
                        url: vm.API_PREFIX + res.data.src
                      })
                      vm.model1.rwInfo.photo=vm.pictures.map(n => n.path).join(',');
                    } else {
                        uni.$u.toast('上传失败');
                    }
                });
            });
        },
        afterFileDelete: function(data) {
          var vm=this
          vm.pictures.splice(data.index, 1);
          vm.model1.rwInfo.photo=vm.pictures.map(n => n.path).join(',');
        },


    toTree() {
      var vm = this;
      if (this.model1.rwInfo.ssgd == ""&&this.model1.rwInfo.rwlx==='工地管理任务') {
        uni.$u.toast("请先选取工地");
      } else {
        var rwlx=''
        if(this.model1.rwInfo.rwlx=='公用管理任务'){
          rwlx='gy'
        }else if(this.model1.rwInfo.rwlx=='工地管理任务'){
          rwlx='gd'
        }else{
          rwlx='qt'
        }
         uni.navigateTo({ url: '/pages/tree/index?loadApi=/mobile/qyjg/xcx/task/api/selectUser.jsp&rwlx='+rwlx+'&ssgdId='+this.model1.rwInfo.entityId});
      }
    },

    getGds(name) {
      var vm = this;
      vm.getAndLoad(
        "获取工地数据",
        vm.WX_ASSETS + "/xcx/task/gd.jsp?name="+name,
        function (res) {
          if(res.data.length>0){
            vm.actions = res.data;
            vm.showSsgd=true
          }else{
            uni.$u.toast("未搜索到对应工地");
            vm.model1.rwInfo.ssgd=""
          }
          
        }
      );
    },

    submit1() {
      var vm = this;

      this.$refs.form1
        .validate()
        .then((res) => {
          delete this.model1.rwInfo.zpry;
          if(this.model1.rwInfo.endTime==''){
            uni.$u.toast("截止时间未填");
            return
          }
          if(this.model1.rwInfo.userIds==''){
            uni.$u.toast("指派人员未填");
            return
          }
          if(this.model1.rwInfo.rwlx==='工地管理任务'&&this.model1.rwInfo.entityId==''){
            uni.$u.toast("工地未选择");
            return
          }
          var postUrl =vm.WX_ASSETS+ "/xcx/task/save.jsp?";
          vm.getAndLoad(
            "保存",
            postUrl + vm.$Util.stringify(this.model1.rwInfo),
            function (res) {
              if (res.success) {
                // uni.$u.toast('提交成功！');
                  
                                  uni.showModal({
                            title: "提示",
                            content: "提交成功",
                            showCancel: false,
                            success: function (res2) {
              uni.navigateTo({
          url: '/pages/content/list?loadJSON=/mobile/qyjg/wxJSON/任务管理/list.json',
        });
                            },
                          });
                          vm.pictures=[];
                vm.model1= {
                rwInfo: {mc: "",endTime: "",content: "",zpry: "",userIds: "",ssgd: "",entityId: "",type:'',address:'',photo:[]
        },
      } 


              }
            }
          );
        })
        .catch((errors) => {
          uni.$u.toast("还有信息未填");
        });
    },
    submit2() {
      var vm = this;
          console.log("🚀 ~ file: index.vue:410 ~ .then ~ (this.model1.rwInfo):", (this.model1.rwInfo))

      this.$refs.form1
        .validate()
        .then((res) => {
          delete this.model1.rwInfo.zpry;
          if(this.model1.rwInfo.endTime==''){
            uni.$u.toast("截止时间未填");
            return
          }
          if(this.model1.rwInfo.userIds==''){
            uni.$u.toast("指派人员未填");
            return
          }
          var postUrl =vm.WX_ASSETS+ "/xcx/task/api/save.jsp?";
          vm.getAndLoad(
            "保存",
            postUrl + vm.$Util.stringify(this.model1.rwInfo),
            function (res) {
              if (res.success) {
                // uni.$u.toast('提交成功！');
                  
                                  uni.showModal({
                            title: "提示",
                            content: "提交成功",
                            showCancel: false,
                            success: function (res2) {
              uni.navigateTo({
          url: '/pages/content/list?loadJSON=/mobile/qyjg/wxJSON/任务管理/list.json',
        });
                            },
                          });
                          vm.pictures=[];
                vm.model1= {
                rwInfo: {mc: "",endTime: "",content: "",zpry: "",userIds: "",ssgd: "",entityId: "",type:'',address:'',photo:[]
        },
      } 


              }
            }
          );
        })
        .catch((errors) => {
          uni.$u.toast("还有信息未填");
        });
    },
    back: function () {
      // #ifdef H5
      history.go(-1);
      // #endif
      // #ifdef MP
      uni.navigateBack();
      // #endif
    },
  },
  onShow() {
    var vm = this;

            let pages = getCurrentPages();
        let currPage = pages[ pages.length - 1];//当前页

                if(currPage.data.callBackData){
            var fData=currPage.data.callBackData
            vm.model1.rwInfo.zpry=fData.map((item)=>{return item.label}).toString();
            vm.model1.rwInfo.userIds=fData.map((item)=>{return item.id}).toString();
            vm.model1.rwInfo.type=fData[0].type
        }
					uni.showLoading({title: '请稍后'});
					var getLocationTimeout = setTimeout(() => {
						uni.hideLoading();
						console.log('获取定位超时，请检查您的网络环境，位置信息是否打开，或检查微信的位置权限。');
					}, 5000);
					vm.getUserLocation().then(res => {
						clearTimeout(getLocationTimeout);
              var wz=res.latitude+','+res.longitude
                    wx.request({
          url: "https://apis.map.qq.com/ws/geocoder/v1/",
          method: "GET",
          data: {
            location: wz,
            key: "RTXBZ-JO3HJ-GS5FQ-XGEE6-YA47V-HABPC",
          },
          success: (res) => {
            vm.model1.rwInfo.address=res.data.result.address;
          },
        });
						uni.hideLoading();
						// vm.position = res;
						// console.log("🚀 ~ file: index.vue:388 ~ vm.getUserLocation ~ res:", res)
            
					}).catch(e => {
						console.log('获取定位失败');
					});



  },
  onLoad(options) {
    var vm=this
        vm.minDate = new Date().getTime()
    //     vm.model1.rwInfo.endTime = uni.$u.timeFormat(
    //   new Date(),
    //   "yyyy-mm-dd  hh:MM:ss"
    // );
  },
};
</script>

<style lang="scss" scoped>
.u-page {
  height: 100vh;
  overflow: hidden;
  background: #fff;
}
.con {
  width: 90vw;
  margin: 0 auto;
}
</style>
